package com.example.springbootpro.notic;


import com.example.springbootpro.exception.BusinessException;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;

import java.util.regex.Pattern;


@Deprecated
public class SqlFilterAspect {

    private static final Pattern SELECT_PATTERN = Pattern.compile("^\\s*SELECT", Pattern.CASE_INSENSITIVE);

    @SneakyThrows
    @Around("execution(* org.springframework.jdbc.core.JdbcTemplate.*(..))")
    public Object filterSql(ProceedingJoinPoint joinPoint)   {
        try {
            Object[] args = joinPoint.getArgs();
             if (args.length > 0 && args[0] instanceof String) {
                String originalSql = (String) args[0];

                 if (isSelectQuery(originalSql) && !containsDeleteCondition(originalSql)) {
                    String modifiedSql = addDeleteCondition(originalSql);
//                    log.info(modifiedSql);
                    args[0] = modifiedSql;
                }
            }
            return joinPoint.proceed(args);
        } catch (Throwable e) {
             throw new BusinessException("500",e.getMessage());
        }
    }

    private boolean isSelectQuery(String sql) {
        return SELECT_PATTERN.matcher(sql).find();
    }

    private boolean containsDeleteCondition(String sql) {
        return sql.toLowerCase().contains("is_delete");
    }

    private String addDeleteCondition(String sql) {
        String upperSql = sql.toUpperCase();
        
        if (upperSql.contains("WHERE")) {
            // 已有WHERE条件，追加AND
            return sql.replaceFirst("(?i)WHERE", "WHERE is_delete = 0 AND");
        } else if (upperSql.contains("GROUP BY") || upperSql.contains("ORDER BY") || upperSql.contains("LIMIT")) {
            // 在GROUP BY/ORDER BY/LIMIT前添加WHERE
            return sql.replaceFirst("(?i)(GROUP BY|ORDER BY|LIMIT)", "WHERE is_delete = 0 $1");
        } else {
            // 简单查询，直接添加WHERE
            return sql + " WHERE is_delete = 0";
        }
    }
}